<template>
    <el-menu
        background-color="whitesmoke"
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        :ellipsis="false"
        @select="handleSelect"
    >

      <el-input v-model="c.title" style="text: relative;top: 0px;font-size: large" placeholder="请输入文章标题..."></el-input>
      <div class="flex-grow"/>
      <el-menu-item >
      <p>剩余时间:{{expiration}}天</p>
    </el-menu-item>
      <el-menu-item>
        <el-button type="primary" plain @click="exportToMd">导出</el-button>
      </el-menu-item>
      <el-menu-item index="user">
        <el-button type="primary"  @click="pushdata()" plain>草稿箱</el-button>
      </el-menu-item>
      <el-menu-item class="popover-item">

        <!--弹出框开始      -->
        <el-popover
            :visible="visible"
            placement="bottom"
            :width="700"
            trigger="click"
            content="this is content, this is content, this is content"
            el-menu-demo
            class="el-popover__popper"
        >
          <template #reference>
            <el-button type="primary" @click="visible=true">发布</el-button>
          </template>
          <div style="font-size: 20px;margin-left: 5px;color: #1D2129">发布文章</div>
          <span class='underline'></span>

          <!--分类按钮开始      -->

          <div style="margin-top: 20px; display: flex; flex-wrap: wrap;">
          <span style="margin-left: 105px; font-size: 15px;color: #1D2129">
            <span style="color: red;">*</span>分类:</span>
            <el-cascader :options="categoryArr" :show-all-levels="false" style="margin-left: 5px"
                         @change="handleChange"/>
            <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 25px ; /* 调整下划线与标题的间距 */"> </span>
            <!--分类按钮开始      -->
            <!-- 添加标签开始       -->
            <span style="margin:5px 0 0 75px;font-size: 15px;color: #1D2129">
          <span style="color: red;">*</span>添加标签:</span>
            <el-form-item>
              <div class="tag-input" >
                <el-checkbox v-for="item in TagList" v-model="selectTags" :label="item.id" size="large" style="margin-left: 10px; ">
                  {{item.tagName}}
                </el-checkbox>
<!--                <a-select mode="tags" style="width: 766px; margin-top: 17px;"-->
<!--                          placeholder="请输入标签(限制长度为1-12)"-->
<!--                          @change="handleChangeTag" size="large" :max-tag-count="5" v-model="selectTags"-->
<!--                          :dropdown-style="{ maxHeight: '170px', overflowY: 'auto' ,}">-->
<!--                  <a-select-option v-for="item in TagList" :key="item.id"-->
<!--                                   v-infinite-scroll="load">-->
<!--                    {{ item.tagName }}-->
<!--                  </a-select-option>-->
<!--                </a-select>-->
              </div>
            </el-form-item>
            <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
            <!-- 添加标签结束       -->
            <!--上传图片开始        -->
            <span style="margin:5px 0 0 85px;font-size: 15px;color: #1D2129">文章封面:</span>
            <el-upload
                v-model:file-list="fileList"
                action="http://123.60.129.240:49380/upload/uploadImage"
                name="file"
                limit="1"
                style="margin-left: 5px;"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image"/>
            </el-dialog>
            <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
            <!--上传图片结束       -->
            <!--编辑摘要开始   -->
            <span style="margin:5px 0 0 75px;font-size: 15px;color: #1D2129">编辑摘要:</span>
            <el-input
                v-model="c.brief"
                :autosize="{ minRows: 6 }"
                maxlength="100"
                placeholder="前100字为摘要"
                show-word-limit
                type="textarea"
                style="width: 500px;margin-left: 5px"
            />
            <span style=" border-bottom: none;
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
            <!--选择公开私密开始-->
            <span style="margin:5px 0 0 75px;font-size: 15px;color: #1D2129">
          <span style="color: red;">*</span>选择状态:</span>
            <el-radio-group v-model="c.isDisplay" style="margin-left: 5px">
              <el-radio :label="0">私密</el-radio>
              <el-radio :label="1">公开</el-radio>
              <!--            <el-radio :label="2">付费解锁</el-radio>-->
            </el-radio-group>
            <!--选择公开私密结束-->
            <span style=" border-bottom: 1px solid #ccc; /* 将下划线颜色设置为灰色 */
                     display: inline-block; /* 使下划线占据一行 */
                     width: 100%; /* 下划线宽度 */
                     margin: 20px ; /* 调整下划线与标题的间距 */"> </span>
            <!--编辑摘要结束     -->

            <!--取消与确认发布按钮开始     -->
            <div style="display: flex; justify-content: center;">
              <el-button type="primary" @click="savedraft()">保存草稿</el-button>
              <el-button style="margin-left: 370px;width: 100px" @click="visible = false">取消</el-button>
              <el-button type="primary" style="margin-left: 20px" @click="post()">确认与发布</el-button>
            </div>
            <!--取消与确认发布按钮结束     -->
          </div>
        </el-popover>

      </el-menu-item>
      <el-menu-item>

        <el-button style="font-size: 20px;height: 55px"
                   text @click="outerVisible = true">
          <el-menu-item>
            <el-icon size="30">
              <Switch/>
            </el-icon>
          </el-menu-item>
        </el-button>
      </el-menu-item>
      <el-avatar
          :size="50"
          src="../gh.webp"
          @click="pushIndex"
      />
    </el-menu>
    <el-dialog v-model="outerVisible" title="切换为富文本编辑器">
      <template #default>
        切换写作模式后，当前内容不会迁移，但会自动保存为草稿。
        <el-dialog
            style="width: 100%;height: 100%"
            v-model="innerVisible"
            width="100%"
            title="Inner Dialog"
            append-to-body
        />
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false" style="position: relative; right: 30px">取消</el-button>
          <router-link to="/text">
            <el-button type="primary">
              确定
            </el-button>
          </router-link>
        </div>
      </template>
    </el-dialog>
    <div ref="divRef" style="height: 600px"/>
</template>

<script setup>
import {AiEditor} from "aieditor";
import "aieditor/dist/style.css"
import {onMounted, onUnmounted, ref} from "vue";
import tokenAxios from "@/http/request/TokenAxios";
import {ElMessage} from "element-plus";
import axios from "axios";
import router from "@/router";
import saveAs from "file-saver"

const c = ref({title: "", brief: "", isDisplay: 0, draft: 0, detail: []});
const categoryArr = ref([]);
const selectTags = ref([])
const TagList = ref([])
const page = ref(0)
const outerVisible = ref(false)
const innerVisible = ref(false)
const divRef = ref();
let aiEditor = null;
const visible = ref(false)

//标签-------------
const handleChangeTag = (value) => {
  console.log(value)
  // 从 TagList 中匹配用户输入的标签，获取对应的标签ID组成数组
  c.value.tagList = TagList.value.filter(tag => value.includes(tag.id)).map(tag => tag.id);
  console.log(c.value.tagList)
};

const load = () => {

  // if (TagList.value.length > 0 && TagList.value.length % 12 !== 0) {
  //   return;
  // }

  page.value++;
  tokenAxios.get('http://123.60.129.240:49282/tag?page=' + page.value)
      .then((response) => {
        if (response.state === 20000) {
          if (response.data.list.length === 0) {
            // 数据库中没有更多数据了，停止发送请求
            return;
          }
          TagList.value = response.data.list;
          console.log(TagList.value)
          console.log(TagList.value.length)
        } else {
          ElMessage.error(response.message)
        }
      })
}

const handleChange = (value) => {
  // value就是选中的值
  // 您可以在这里将value赋值给c的上传参数
  // console.log(typeof value)
  c.value.categoryId = parseInt(value[value.length - 1]);
}


const loadCategories = () => {
  tokenAxios.get(BASE_URL + ':49282/categories/tree')
      .then((response) => {
        if (response.state === 20000) {
          categoryArr.value = response.data;
        }
      })
}


//上传图片开始-----------
const handleSuccess = (response, file, fileList) => {
//response = JsonResult
  //判断上传的文件是图片还是视频
  if (file.raw.type.includes('image')) {
    //把上传成功的图片路径装进内容对象c里面
    c.value.coverUrl = response.data;
  } else {
    // 如果上传的不是图片路径，返回错误提示
    ElMessage.error('上传的文件类型不正确!');
    return;
  }
}
const handleRemove = (uploadFile, uploadFiles) => {
  if (uploadFile.raw.type.includes('image')) {
    // 把上传成功的图片路径装进内容对象c里面
    c.value.imgUrl = null;
    console.log(uploadFile.response.data);
    // 发出删除文件的请求
    let url = uploadFile.response.data; // 得到当前文件的路径
    axios.post(BASE_URL + ':49380/upload/deleteImage?url=' + url).then((response) => {
      if (response.data.state == 20000) {
        ElMessage.success("删除文件完成!");
      }
    })
  }
}
const exportToMd = () => {
  if (confirm("是否导出?")){
    if (typeof aiEditor.getMarkdown() !== 'undefined' && aiEditor.getMarkdown().trim() !== ''){
      const blob = new Blob([aiEditor.getMarkdown()], {type: 'text/markdown;charset=utf-8'});
      // 使用FileSaver保存文件
      saveAs(blob, 'output.md');
    }else {
      ElMessage.error('内容为空，无法导出！')
    }
  }
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
//上传图片结束-----------


const loadDraft = (articleId) => {
  console.log(articleId)
  console.log(getUser().id)
  tokenAxios.get(BASE_URL + ':49282/article/selectDraftDetail/' + getUser().id + '/' + articleId)
      .then((response) => {
        if (response.state === 20000) {
          c.value = response.data;
          console.log(response);
          if (aiEditor) {
            aiEditor.setContent(c.value.detail);
            console.log("===================================")
            console.log(c.value.detail)
            console.log(aiEditor.getMarkdown(c.value.detail))
          }
        }

      })
}


let textarea = ref('')
const post = () => {
  if (c.value.title.trim() == '') {
    ElMessage.error('标题不能为空!');
    return;
  }

//把富文本编辑器里面的内容取出   取出的是包含html标签的内容
  console.log(aiEditor.getMarkdown());
  c.value.detail = aiEditor.getMarkdown();
//设置摘要 (正文的前30个字符作为摘要)   editor.txt.text()得到纯文本内容(不包括标签)
  c.value.brief = aiEditor.getMarkdown().slice(0, 30);
  tokenAxios.post(BASE_URL + ':49282/article/add-new', c.value)
      .then((response) => {
        console.log(c.value)
        if (response.state == 20000) {
          ElMessage.success("发布完成!");
          router.push('/creation/banner');//跳转到文章管理页面
        } else {
          ElMessage.error(response.message)
        }
      })
}

const savedraft = () => {
  //把富文本编辑器里面的内容取出   取出的是包含html标签的内容
  c.value.detail = aiEditor.getMarkdown();
//设置摘要 (正文的前30个字符作为摘要)   editor.txt.text()得到纯文本内容(不包括标签)
  c.value.brief = aiEditor.getMarkdown().slice(0, 30);
  c.value.draft = 1;
  c.value.editortype = 0;
  tokenAxios.post(BASE_URL + ':49282/article/add-new', c.value)
      .then((response) => {
        console.log(c.value)
        if (response.state == 20000) {
          ElMessage.success("发布完成!");
          router.push('/creation/data');//跳转到文章管理页面
        } else {
          ElMessage.error(response.message)
        }
      })
}

//是否具有使用ai编辑器的权限
let permission = false;
const pushdata = () => {
  router.push('/creation/data')
}
const checkExpiration = () => {
  tokenAxios.post(BASE_URL + ':49283/reward/checkExpiration').then((response) => {
    if (response.state === 20000) {
      permission = response.data;
      console.log(permission);
      if (permission === false){
        router.push('/text');
        ElMessage.error("请先解锁AI编辑器!")
      }
    } else {
      ElMessage.error("请先登录!")
      router.push('/');
    }
  })
}
let expiration= ref(0);
const selectTime=()=>{
  tokenAxios.post(BASE_URL+':49283/reward/selectExpiration').then((respose)=>{
    if (respose.state===20000){
      console.log(respose.data);
      expiration.value=respose.data/24;
    }
  })
}
onMounted(() => {
  checkExpiration();
  selectTime();
  loadCategories();
  load();

  let id = new URLSearchParams(location.search).get('id');
  if (id != null) {
    loadDraft(id);
  }
  aiEditor = new AiEditor({
    element: divRef.value,
    placeholder: "点击输入内容...",
    content: c.value.detail,

    ai: {
      models: {
        spark: {
          protocol: "wss",
          appId: "64b424ed",
          apiKey: "468723324d593bdece2b9f7cd74cba22",
          apiSecret: "NzM1YzgxZTJkMDM1YWY4OTA0ZjgxNjZh",
        }
      }
    }
  });


});

const pushIndex = () => {
  router.push('/index')
}
onUnmounted(() => {
  aiEditor && aiEditor.destroy();
})
</script>

